#!/bin/bash

# show build env vars
echo "build env vars:"
env

CAE_COMMON_VARS_FILE_PATH="env/cae_common_vars"
CAE_COMMON_VARS_PLACE_HOLDER="##CAE_COMMON_VARS_PLACE_HOLDER##"
DIFY_COMMON_VARS_FILE_PATH="env/dify_common_vars"
DIFY_COMMON_VARS_PLACE_HOLDER="##DIFY_COMMON_VARS_PLACE_HOLDER##"

# Check if the replace_env_vars_placeholders.sh script has execution permissions. If not, add them.
if [ ! -x replace_env_vars_placeholders.sh ]; then
    chmod +x replace_env_vars_placeholders.sh
fi

# Define the list of Dockerfile paths
dockerfile_paths=(
    "service/api/Dockerfile"
    "service/web/Dockerfile"
    "service/worker/Dockerfile"
    "middleware/nginx/Dockerfile"
    "middleware/plugin-daemon/Dockerfile"
    "middleware/sandbox/Dockerfile"
    "middleware/ssrf-proxy/Dockerfile"
)

# Iterate through the list of Dockerfile paths
for dockerfile_path in "${dockerfile_paths[@]}"; do
    # Check if the Dockerfile exists
    if [ ! -f "$dockerfile_path" ]; then
        echo "Error: The $dockerfile_path file was not found! Skipping this Dockerfile."
        continue
    fi
    # Call the replace_env_vars_placeholders.sh script and pass the env_vars file path, Dockerfile path, and placeholder name
    bash replace_env_vars_placeholders.sh "$CAE_COMMON_VARS_FILE_PATH" "$dockerfile_path" "$CAE_COMMON_VARS_PLACE_HOLDER"
    bash replace_env_vars_placeholders.sh "$DIFY_COMMON_VARS_FILE_PATH" "$dockerfile_path" "$DIFY_COMMON_VARS_PLACE_HOLDER"
done

echo "The environment variable replacement operation is complete for all valid Dockerfiles." 